package com.network.controller;

import com.network.pojo.User;
import com.network.pojo.UserInfo;
import com.network.service.UserInfoService;
import com.network.service.UserService;
import org.apache.coyote.Request;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;


@Controller
public class LoginAndRegisterController {


    @Autowired
    UserService userService;

    @Autowired
    UserInfoService userInfoService;


    /**
     * 进入登录界面
     * @param message
     * @param model
     * @return
     */
    @GetMapping("/login")
    public String log(@RequestParam(value = "message",required = false) String message, Model model) {
        String mes = message == null ? "" : message;
        model.addAttribute("message",mes);
        return "login";
    }


    /**
     * 进行账号密码的验证
     * @param user
     * @param redirectAttributes
     * @param session
     * @param response
     * @return
     */
    @PostMapping("/login")
    public String login(User user, RedirectAttributes redirectAttributes, HttpSession session, HttpServletResponse response) {

        UserInfo userInfo = userService.login(user.getUsername(), user.getPassword());

        if (userInfo == null) {
            String message = "您输入的的账号密码有误!请重新输入";
            redirectAttributes.addAttribute("message",message);
            return "redirect:/login";
        }

        Cookie cookie = new Cookie(user.getUsername(),user.getUsername());
        cookie.setMaxAge(60*60*4);
        response.addCookie(cookie);
        session.setAttribute("user",userInfo);

        return "redirect:/tmp";
    }

    /**
     * 获取在本机登录过的账号的头像
     * @param request
     * @param username
     * @return
     */
    @ResponseBody
    @GetMapping("/getImage")
    public String getImage(HttpServletRequest request,@RequestParam("username") String username) {
        Cookie[] cookies = request.getCookies();
        boolean flag = false;
        for (Cookie cookie : cookies) {
            if(username.equals(cookie.getName())) {
                flag = true;
                break;
            }
        }

        if (flag) {
            UserInfo userInfo = userInfoService.findUserInfoByUsername(username);
            if(userInfo == null) {
                return "";
            }
            return userInfo.getPicture();
        }

        return "";
    }


    /**
     * 进入注册界面
     * @return
     */
    @GetMapping("/register")
    public String reg() {
        return "register";
    }


    /**
     * 进行注册
     * @param user
     * @param image
     * @return
     */
    @PostMapping("/register")
    public String register(User user, @RequestParam(value = "image",required = false)MultipartFile image) {

        if(image != null && image.getSize() > 0) {
            String originalFilename = image.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.indexOf("."));
            String realName = UUID.randomUUID().toString() + suffix;


            /**
             * 不应该这样写的
             */
//            File file = new File("src/main/resources/pictures");
//            File file1 = new File(file.getAbsolutePath() +"/"+ realName);
//            Resource resource = new ClassPathResource("pictures");
            try {


                File file = new File("D:/pictures");


                image.transferTo(new File(file.getAbsolutePath()+"/"+realName));
//
//                FileInputStream fileInputStream = new FileInputStream(file1);
//                File file2 = new File(resource.getFile().getAbsolutePath()+"/"+realName);
//                FileOutputStream fileOutputStream = new FileOutputStream(file2);
//                byte[] bytes = new byte[1024];
//                int len = -1;
//                while ((len = fileInputStream.read(bytes)) != -1) {
//                    fileOutputStream.write(bytes,0,len);
//                }
//
                userService.register(user,realName,true);

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            userService.register(user,null,true);
        }

        return "redirect:/login";
    }


    /**
     * 检测是否存在这一个用户
     * @param username
     * @return
     */
    @ResponseBody
    @GetMapping("/check")
    public User check(@RequestParam("username") String username) {
        User user = userService.checkUsername(username);
        System.out.println("2:"+user);
        return user;
    }


}
